import { createContext, useContext, useState, useEffect } from 'react';
import type { ReactNode, Theme, ThemeId } from '../types/theme';
import { getThemeById } from '../config/themes';

interface ThemeContextType {
  theme: Theme;
  themeId: ThemeId;
  setTheme: (themeId: ThemeId) => void;
  toggleTheme: () => void;
}

const ThemeContext = createContext<ThemeContextType | undefined>(undefined);

interface ThemeProviderProps {
  children: ReactNode;
}

export function ThemeProvider({ children }: ThemeProviderProps) {
  const [themeId, setThemeId] = useState<ThemeId>(() => {
    const saved = localStorage.getItem('theme-id');
    return (saved as ThemeId) || 'vibrancy-orange';
  });

  const theme = getThemeById(themeId);

  const setTheme = (newThemeId: ThemeId) => {
    setThemeId(newThemeId);
    localStorage.setItem('theme-id', newThemeId);
  };

  const toggleTheme = () => {
    const nextTheme: ThemeId = theme.isDark ? 'vibrancy-orange' : 'dark';
    setTheme(nextTheme);
  };

  useEffect(() => {
    const root = document.documentElement;
    const colors = theme.colors;

    // 辅助函数：将hex颜色转换为RGB
    const hexToRgb = (hex: string) => {
      const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
      return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
      } : null;
    };

    Object.entries(colors.primary).forEach(([key, value]) => {
      root.style.setProperty(`--color-primary-${key}`, value);
      const rgb = hexToRgb(value);
      if (rgb) {
        root.style.setProperty(`--color-primary-${key}-rgb`, `${rgb.r}, ${rgb.g}, ${rgb.b}`);
      }
    });

    Object.entries(colors.secondary).forEach(([key, value]) => {
      root.style.setProperty(`--color-secondary-${key}`, value);
      const rgb = hexToRgb(value);
      if (rgb) {
        root.style.setProperty(`--color-secondary-${key}-rgb`, `${rgb.r}, ${rgb.g}, ${rgb.b}`);
      }
    });

    root.style.setProperty('--color-success', colors.success);
    root.style.setProperty('--color-warning', colors.warning);
    root.style.setProperty('--color-error', colors.error);
    root.style.setProperty('--color-info', colors.info);

    Object.entries(colors.background).forEach(([key, value]) => {
      root.style.setProperty(`--color-bg-${key}`, value);
    });

    Object.entries(colors.text).forEach(([key, value]) => {
      root.style.setProperty(`--color-text-${key}`, value);
    });

    Object.entries(colors.border).forEach(([key, value]) => {
      root.style.setProperty(`--color-border-${key}`, value);
    });

    root.className = theme.isDark ? 'dark' : 'light';
  }, [theme]);

  return (
    <ThemeContext.Provider value={{ theme, themeId, setTheme, toggleTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}

export function useTheme(): ThemeContextType {
  const context = useContext(ThemeContext);
  if (!context) {
    throw new Error('useTheme must be used within a ThemeProvider');
  }
  return context;
}